class DBPool {
  constructor() {
    this.mysql = require("mysql");
    this.config = require("./db.config");
    //1.创建mysql连接对象
    this.pool = this.mysql.createPool(this.config);
  }
  query(sql, params, callBack) {
    //2.打开
    this.pool.getConnection((err, connection) => {
      if (err) {
        console.log("数据库连接失败");
        throw err;
      }
      //3.执行sql查询
      connection.query(sql, params, (err, results, fields) => {
        //4.释放连接
        connection.release();
         // connection.destroy();//销毁链接
        if (err) {
          console.log("数据库操作失败");
          throw err;
        }
        callBack && callBack({ results, fields });
      });
    });
  }

  queryAsync(sql, params) {
    const self = this;
    return new Promise((resolve, reject) => {
      this.pool.getConnection((err, connection) => {
        if (err) {
          console.log("数据库连接失败");
          reject(err);
          return;
        }
        connection.query(sql, params, (err, results, fields) => {
          connection.release(); 
          // connection.destroy();
          if (err) {
            console.log("数据库操作失败");
            reject(err);
            return;
          }
          resolve({
            results,
            fields,
          });
        });
      });
    });
  }
}

module.exports = new DBPool();
